<?php
require_once "json.php";
require_once "xml.php";
require_once "session.php";
require_once "message.php";
class NewBudget_File{
	private $pagesize=15;
	public function __construct(){
		$this->xmldb=new NewBudget_XmlDb("../db/files.xml");
	}
	private function copyXml($sPath,$dPath){
		$isCache=0;
		$dh=opendir($sPath);
		while(false!==($file=readdir($dh))){
			if(is_dir($sPath.$file))	continue;
			copy($sPath.$file,$dPath.$file);
			$isCache=1;
		}
		closedir($dh);
		return $isCache;
	}
	public function newFile($args){
		if(false==$this->isValidCellNo($args["wellno"]))
			return array("result"=>0,"reason"=>"相同名称的井号已经存在");//0:failure 1:success
		$fileName=chr(mt_rand(65,90)).chr(mt_rand(65,90)).chr(mt_rand(65,90)).mktime();
		mkdir("../db/budget/".$fileName,0766);//copy from book/oiltest/*.xml
		$isCache=$this->copyXml("../book/".$args["tempno"]."/cache/","../db/budget/".$fileName."/");//判断是否从cache里读取
		if(0==$isCache)	$this->copyXml("../book/".$args["tempno"]."/","../db/budget/".$fileName."/");
		$this->reWriteXML("../db/budget/".$fileName,"form_basic.xml",array("D1"=>$args["wellno"]));
		$this->reWriteXML("../db/budget/".$fileName,"form_face.xml",array("B4"=>$args["wellno"],"B13"=>date("Y-m-d")));
		$node=$this->makeNewFileNode($args["wellno"],$fileName,$isCache,$args["tempno"]);
		if(true==$this->xmldb->addNode("/budgets",$node)){
			$this->xmldb->saveDoc();//正式保存XML
			//newMessage("");
			return	array("result"=>1,"fileinfo"=>$this->getFileInfo($node));
		}
		else
			return showesg();
	}
	private function getFileInfo($node){
		return array("filename"=>$node->getAttribute("filename"),
					"wellno"=>$node->getAttribute("wellno"),
					"createdate"=>$node->getAttribute("createdate"),
					"author"=>$node->getAttribute("author"),
					"status"=>$node->getAttribute("status"),
					"tempno"=>$node->getAttribute("tempno"),
					"iscache"=>$node->getAttribute("iscache"));
	}
	private function isValidCellNo($wellNo){
		if($this->xmldb->xselect("budget[@wellno='".$wellNo."']")->length>0)	return false;
		return true;
	}
	private function makeNewFileNode($wellno,$filename,$isCache,$tempno){
		$bNode=$this->xmldb->doc->createElement("budget");
		$bNode->setAttribute("filename",$filename);
		$bNode->setAttribute("wellno",$wellno);
		$bNode->setAttribute("createdate", date("Y-m-d H:i:s"));//取得系统时间
		$bNode->setAttribute("author",NewBudget_Session::get("username"));
		$bNode->setAttribute("status","new");
		$bNode->setAttribute("iscache",$isCache);
		$bNode->setAttribute("tempno",$tempno);
		return $bNode;
	}
	private function reWriteXML($filename,$bookname,$args){
		$xmlbook=new NewBudget_XmlDb($filename."/".$bookname);
		//echo(NewBudget_Json::encode($args));
		foreach($args as $key=>$value){
			//echo($key);
			preg_match("/([A-Z]+)(\d+)/",$key,$ma);
			if(false==$xmlbook->changeValue("row[@index='".$ma[2]."']/".$ma[1],"value",$value))	return false;
		}
		$xmlbook->saveDoc();
		return true;
	}
	public function saveFile($args){
		$wellno=$args["pake"]["wellno"];
		$pake=$args["pake"]["datapake"];
		$fileInfo=$this->getFileInfo($this->xmldb->xselect("budget[@wellno='".$wellno."']")->item(0));
		if(NewBudget_Session::get("username")!=$fileInfo["author"])
			if(false==isAdmin())	return array("result"=>0,"reason"=>"你没有权限");
		if("new"!=$fileInfo["status"]&&"reject"!=$fileInfo["status"]&&"draft"!=$fileInfo["status"])
			if(false==isAdmin())	return array("result"=>0,"reason"=>"文件不能被修改");
		foreach($pake as $file=>$datas){
			if(false==$this->reWriteXML("../db/budget/".$fileInfo["filename"],"form_".$file.".xml",$datas))	return showesg();
		}
		if("new"==$fileInfo["status"])//新建的定额，只要第一次保存就变为draft
			$this->changeAtt(Array("wellno"=>$wellno,"attrs"=>Array("status"=>"draft")));
		return array("result"=>1);

	}
	public function saveCache($args){
		$pake=$args["pake"]["datapake"];
		$tempno=$args["tempno"];
		$this->copyXml("../book/".$tempno."/","../book/".$tempno."/cache/");
		foreach($pake as $file=>$datas){
			if(false==$this->reWriteXML("../book/".$tempno."/cache","form_".$file.".xml",$datas))	return showesg("");
		}
		return Array("result"=>1);
	}
	public function changeAtt($args){
		foreach($args["attrs"] as $att=>$value){
			if("wellno"==$att)	continue;
			if("status"==$att&&"commit"==$value)	newMessage($args["wellno"]."已经提交",$args["wellno"]."已经提交，请审核");
			if(false==$this->xmldb->changeValue("budget[@wellno='".$args["wellno"]."']",$att,$value))	return showesg();
		}
		$this->xmldb->saveDoc();
		return Array("result"=>1);
	}
	public function listBudget($args){
		$page=$args["page"];
		//echo $page;
		$begin=($page-1)*$this->pagesize;
	//	NewBudget_Session::set("userrole","guest");
	//	NewBudget_Session::set("username","蓝鸟");
		if(isAdmin())
			$xql="budget";
		elseif(isGuest())
			$xql="budget[@status='freeze']";
		else
			$xql="budget[@author='".NewBudget_Session::get("username")."' or @status='freeze']";
		//echo $begin;
		$rs=$this->xmldb->xselect($xql);
		$num=$rs->length;
		$tem=$num % $this->pagesize;
		$showpagecount=($tem==0)?$num/$this->pagesize:($num-$tem)/$this->pagesize+1;
		$result=Array();
		$l=0;
		//echo $begin.'aa'.$end;
		for($i=$begin;$i<$num;$i++){
			array_push($result,$this->getFileInfo($rs->item($i)));
			if(++$l==$this->pagesize)	break;
		}
		return Array("list"=>$result,"pagecount"=>$showpagecount,"page"=>$page);
	}
	public function checkBudget($args){
		$wellno=$args["wellno"];
		if(false==isAdmin())	return showesg("你没有权限");
		//$chkResult=(false==$args["result"])?"reject":"freeze";
		$reason=$args["reason"];
		if(false==$args["result"]){
			$chkResult="reject";
			newMessage($wellno."未通过审核","未通过审核的原因是：$reason");
		}
		else{
			$chkResult="freeze";
			newMessage($wellno."通过审核",$wellno."通过审核，数据已经封存。");
		}
		return $this->changeAtt(Array("wellno"=>$wellno,"attrs"=>Array("status"=>$chkResult)));
	}
	public function delBudget($args){
		$wellno=$args["wellno"];
		$filePath=$args["filepath"];
		if(false==$this->canDel($wellno))	return showesg("你没有权限");
		$this->xmldb->xselect("/budgets")->item(0)->removeChild($this->xmldb->xselect("budget[@wellno='".$wellno."']")->item(0));
		$this->xmldb->saveDoc();
		if($this->delBudgetDir("../db/budget/".$filePath))	return Array("result"=>1);
		else	return showesg("服务器错误");
	}
	private function canDel($wellno){
		if(isAdmin())	return true;
		if(NewBudget_Session::get('username')==$this->xmldb->xselect("budget[@wellno='$wellno']")->item(0)->getAttribute("author"))	return true;
		return false;
	}
	private function delBudgetDir($path){
		$dh=opendir($path);
		while(false!==($file=readdir($dh))){
			if("dir"==filetype($path."/".$file))	continue;
			unlink($path."/".$file);
		}
		closedir($dh);
		return rmdir($path);
	}
}
checkIsLogin();//是否登录或者登录过期
$jsonStr=NewBudget_Json::decode($_POST["json"]);
$fileObj=new NewBudget_File();
switch($_POST["action"]){
	case "newFile":
		$result=$fileObj->newFile($jsonStr);
		break;
	case "save":
		//echo $_POST["json"];
		$result=$fileObj->saveFile($jsonStr);
		break;
	case "savecache":
		$result=$fileObj->saveCache($jsonStr);
		break;
	case "changeatt":
		$result=$fileObj->changeAtt($jsonStr);
		break;
	case "listbudget":
		$result=$fileObj->listBudget($jsonStr);
		break;
	case "check":
		$result=$fileObj->checkBudget($jsonStr);
		break;
	case "delbudget":
		$result=$fileObj->delBudget($jsonStr);
		break;
}
echo NewBudget_Json::encode($result);
?>